<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller as BaseController;
use App\Http\Requests\RolesRequest;
use App\Http\Responses\CustomResponse;
use App\Services\admin\RoleService;
use Illuminate\Http\Request;

/**
 * 角色管理
 */
class RoleController extends BaseController
{
    /**
     * 列表
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
     */
    public function index(Request $request)
    {
        $list = RoleService::getPageData($request->all());

        return CustomResponse::success($list);
    }

    /**
     * 列表
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
     */
    public function getRole(Request $request)
    {
        $list = RoleService::getData($request->all());
        $returnArray = [];
        foreach ($list as $key => $item) {
            $returnArray[] = [
                'label' => $item->name,
                'value' => $item->id,
            ];
        }

        return CustomResponse::success($returnArray);
    }

    /**
     * 创建/编辑
     *
     * @param  Request  $request
     * @return void
     */
    public function store(RolesRequest $request)
    {
        if ($request->input('id')) {
            // 编辑
            $requestAll = $request->all(['id', 'name', 'status', 'permissions', 'desc']);

            $id = RoleService::edit($requestAll['id'], $requestAll);
            if ($id) {
                return CustomResponse::success($id, '编辑成功');
            } else {
                return CustomResponse::error('编辑失败');
            }
        } else {
            // 创建
            $requestAll = $request->all(['name', 'status', 'permissions', 'desc']);

            $result = RoleService::create($requestAll);
            if ($result) {
                return CustomResponse::success($result->id, '创建成功');
            } else {
                return CustomResponse::error('创建失败');
            }
        }
    }

    /**
     * 删除
     *
     * @return void
     */
    public function destroy(Request $request, $id)
    {
        $id = RoleService::destroy(explode(',', $id));
        if ($id) {
            return CustomResponse::success($id, '删除成功');
        } else {
            return CustomResponse::error('删除失败');
        }
    }
}
